package ajaxjs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import java.util.logging.Logger;
public class Util {
	public static final boolean isJDK7 = System.getProperty("java.version").contains("1.7.");
	 
	public static final java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
			"yyyy-MM-dd");
	public static final java.text.SimpleDateFormat dateFormat_full = new java.text.SimpleDateFormat(
			"MM-dd HH:mm");

	/**
	 * 自带日志 TODO
	 * @param msg
	 * @param isWARNING
	 */
	public static void log(String msg, Boolean isWARNING) {
		Logger log = Logger.getLogger("sp42:::::::");
		
		if (isWARNING == null)
			log.log(java.util.logging.Level.INFO, "sp42:::::::" + msg);
		else if (isWARNING == true)
			log.log(java.util.logging.Level.WARNING, "sp42:::::::" + msg);
	}
	public static void log(String msg, Object obj) {
		Logger log = Logger.getLogger(obj.getClass().getName());
		log.log(java.util.logging.Level.INFO, obj.getClass().getName() + msg);
	}
	public static void log(String msg, Class<?> cls) {
		Logger log = Logger.getLogger(cls.getName());
		log.log(java.util.logging.Level.INFO, msg);
	}

	
	public void getLogger(String msg, Throwable e){
		
	}
	
	/**
	 * 这里需要强制捕获异常。 中文乱码：http://s.yanghao.org/program/viewdetail.php?i=54806
	 * 
	 * @param rawBase64
	 *            [description]
	 * @return [description]
	 */
	public static String base64Decode(String rawBase64) {
		sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
		try {
			decoder.decodeBuffer(rawBase64);
			byte[] bbb = decoder.decodeBuffer(rawBase64);
			return new String(bbb, "UTF-8");
		} catch (java.io.IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 
	 * @param request
	 * @return
	 */
	public static String getBasePath(HttpServletRequest request){
		return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
	}

	/**
	 * 输入一个相对地址，补充成为绝对地址
	 * @param request
	 * @param relativePath
	 * @return 绝对地址
	 */
	public static String Mappath(HttpServletRequest request, String relativePath){
		String absoPath = null;
		absoPath = request.getServletContext().getRealPath(relativePath);
		
		return absoPath;
	}

	/**
	 * Java String 有 split 却没有 join，这里实现一个
	 * @param arr
	 * @param join
	 * @return
	 */
	public static String stringJoin(String[] arr, String join) {
		StringBuffer sb = new StringBuffer();
		
		for (int i = 0; i < arr.length; i++) {
			if (i == (arr.length - 1)) {
				sb.append(arr[i]);
			} else {
				sb.append(arr[i]).append(join);
			}
		}

		return new String(sb);
	}
	
	/**
	 * Java String 有 split 却没有 join，这里实现一个
	 * @param arr
	 * @param join
	 * @return
	 */
	public static String stringJoin(java.util.List<String> arr, String join) {
		StringBuffer sb = new StringBuffer();
		
		for (int i = 0; i < arr.size(); i++) {
			if (i == (arr.size() - 1)) {
				sb.append(arr.get(i));
			} else {
				sb.append(arr.get(i)).append(join);
			}
		}

		return new String(sb);
	}
	
	/**
	 * 也是 join，不过输入的参数不是数组而是 hash。
	 * @param requestPair
	 * @return
	 */
	public static String HashJoin(Map<String, String> requestPair, String div) {

		String [] pairs = new String[requestPair.size()];
		
		int i = 0;
		for(String key : requestPair.keySet()){
			String pair = key + "=" + requestPair.get(key).toString();
			pairs[i++] = pair;
		}
		
		return stringJoin(pairs, div);
	}
	public static String HashJoin(Map<String, String> requestPair) {

		String [] pairs = new String[requestPair.size()];
		
		int i = 0;
		for(String key : requestPair.keySet()){
			String pair = key + "=" + requestPair.get(key).toString();
			pairs[i++] = pair;
		}
		
		return stringJoin(pairs, "&");
	}
	
	/**
	 * 读取流
	 * @param connection
	 * @return
	 * @throws java.io.IOException 
	 */
	public static String readStream(InputStream is){
		BufferedReader reader = null;
		
		StringBuffer result = new StringBuffer();
		String line = null;
		
		try{
		    reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
		   
			while ((line = reader.readLine()) != null){
				result.append(line);
				// lines = new String(line.getBytes(), "utf-8");
			}
		}catch(IOException e) {
			System.out.println("读取流失败！");
			e.printStackTrace();
		}finally{
		    if(reader != null)
				try {
					reader.close();
				} catch (IOException e) {}
		}
		
		return result.toString();
	}
	
	
	public static void main(String[] args){
//		String[]  arr = {"1", "2"};
//		
//		System.arraycopy(arr, 1,arr,0,arr.length-1-0);
//		String str = String.format("fdf%s,%s", (Object[])arr);
//		System.out.println(str);
	
		catchException(new Exception("dfdfds"), "fdfds %s 434 %s 35", "1", "2");
	}
	
	
	private static String msgFormat(String[] arr){
		String strTpl = new String(arr[0]);
		System.arraycopy(arr, 1, arr, 0, arr.length - 1 - 0); // remove the first element
		
		return String.format(strTpl, (Object[])arr);
	}
	
	public static void catchException(Throwable ex, String...msg){
		if(msg.length == 1)
			System.err.println(msg);
		else{
			System.err.println(msgFormat(msg));
		}
	}
	
	/**
	 * 用于 UI 列表输出的检测
	 * @param arr
	 * @return
	 */
	public static boolean isNotNull(Map<?, ?>[] arr){
		return arr != null && arr.length > 0;
	}
	
	public static final String emptyString = "";
	
	public static boolean isEmptyString(String str){
		boolean isEmptyString = false;
		
		if(str == null || emptyString.equals(str) || emptyString.equals(str.trim()))
			isEmptyString = true;
		
		return isEmptyString;
		
	}
	
	/**
	 * 自动抛出异常
	 * @param str
	 * @param expMsg
	 * @return
	 */
	public static boolean isEmptyString(String str, String expMsg){
		boolean isEmptyString = false;
		if(isEmptyString(str)){
			isEmptyString = true;
			throw new NullPointerException(expMsg);
		}
		
		return isEmptyString;
	}
}
